//
//  JiaoYiOrderDetailViewController.m
//  ChinaA
//
//  Created by Mxionlly on 2018/11/6.
//  Copyright © 2018 Evan. All rights reserved.
//

#import "JiaoYiOrderDetailViewController.h"
#import "JiaoYiPageHeadView.h"
#import "JiaoYiDetailViewCell.h"
#import "taskJiaoYiService.h"
#import "HomePassWordView.h"
#import <Masonry.h>
#import "JiaoYiSuccessViewController.h"

@interface JiaoYiOrderDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView    *tableView;
@property (nonatomic,assign)NSInteger      type;//0：获取卖出订单，1：获取买入订单
@property (nonatomic,strong)dataOrderBuyAndSaleInfo *model;
@property (nonatomic,strong)JiaoYiPageHeadView *headView;
@property (nonatomic,strong)UIButton       *buyButton;
@property (nonatomic,strong)    HomePassWordView*   viewPassword;
@end

@implementation JiaoYiOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.type == 0 ? @"卖单详情" :@"买单详情";
    [self changeHeadView];
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}

- (id)initWithType:(NSInteger )type model:(dataOrderBuyAndSaleInfo *)model{
    self = [super init];
    if (self) {
        self.type = type;
        self.model = model;
        self.headView.lbTurnoverRate.text = [NSString stringWithFormat:@"%@%@",self.model.TurnoverRate,@"%"];
        self.headView.labelTurnoverCount.text = [NSString stringWithFormat:@"%ld",(long)self.model.TurnoverCount];
        self.headView.lbID.text = self.model.UserName;
    }
    return self;
}

#pragma mark - init
-(UIButton *)buyButton{
    if (!_buyButton) {
        _buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _buyButton.frame = CGRectMake(30, 30, KScreenWidth - 60, 40);
        _buyButton.titleLabel.textColor = [UIColor whiteColor];
        _buyButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_buyButton setTitle:self.type == 0 ? @"立即买入" : @"立即卖出" forState:UIControlStateNormal];
        [_buyButton setBackgroundImage:[UIImage imageNamed:@"icon_button"] forState:UIControlStateNormal];
        [_buyButton addTarget:self action:@selector(btnSubmitOrder:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buyButton;
}

-(JiaoYiPageHeadView *)headView
{
    if (!_headView) {
        _headView = [JiaoYiPageHeadView getTopDetailView];
    }
    return _headView;
}

#pragma mark - 支付密码

-(HomePassWordView*)viewPassword{
    if (!_viewPassword ){
        _viewPassword = [[[NSBundle mainBundle] loadNibNamed:@"HomePassWordView" owner:nil options:nil] objectAtIndex:0];
        [_viewPassword initUI];
        [self.view addSubview:_viewPassword];
        _viewPassword.hidden = YES;
        [_viewPassword mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.top.offset(0);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];
    }
    return _viewPassword;
}


#pragma mark - tableviewDelegate

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor  = [UIColor clearColor];
        _tableView.scrollEnabled = YES;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

-(CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 150;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.headView;
}

-(CGFloat )tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 100)];
    [footerView addSubview:self.buyButton];
    return footerView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.type + 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if (self.type == 1) {
            return 110;
        }
        return 90;
    }
    return 130;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        JiaoYiDetailViewCell *cell = [JiaoYiDetailViewCell cellWithTableView:tableView index:indexPath.row];
        cell.lbChinaANumber.text = [NSString stringWithFormat:@"数量:%@个",self.model.ChinaANumber];
        cell.lbPriceRMB.text = [NSString stringWithFormat:@"单价:%@CNY",self.model.PriceRMB];
        cell.floatHidePrice = self.model.PriceRMB;
        cell.lbLimit.text = [NSString stringWithFormat:@"限额:%@-%@",self.model.LimitMix,self.model.LimitMax];
        cell.lbServiceCharge.text = [NSString stringWithFormat:@"手续费:%@%@",self.model.ServiceCharge,@"%"];
        cell.PriceCountRMB.text =[NSString stringWithFormat:@"%@CNY",self.model.PriceCountRMB];
        if (self.type == 0) {
            cell.lbServiceCharge.hidden = YES;
        }
        return cell;
    }
    JiaoYiDetailViewCell *cell = [JiaoYiDetailViewCell cellWithTableView:tableView index:indexPath.row];
    [cell.allbutton addTarget:self action:@selector(allbuy) forControlEvents:UIControlEventTouchUpInside];
    [cell.numField addTarget:self action:@selector(txtEditChanged:) forControlEvents:UIControlEventEditingChanged];
    return cell;
}

-(void)allbuy
{
    JiaoYiDetailViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell.numField.text = [NSString stringWithFormat:@"%.2f",[self.model.ChinaANumber floatValue]];
    cell.lbPrice.text = [NSString stringWithFormat:@"%.2f",[self.model.ChinaANumber floatValue] * [self.model.PriceRMB floatValue]];
}

#pragma mark - 提交订单买卖

-(void)btnSubmitOrder:(UIButton*)sender{

    if (self.type == 1) {
        JiaoYiDetailViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        CGFloat floatCount = [cell.numField.text floatValue];
        if (floatCount <= 0) {
            [DKProgressHUD showErrorWithStatus:@"请输入正确的数量"];
            return;
        }
    }
    
    ///进入输入密码的模块
    self.viewPassword.hidden = NO;
    __block JiaoYiOrderDetailViewController *  blockSelf = self;
    self.viewPassword.blockSubmit = ^(NSString *pwd) {
        [blockSelf tiOrder:pwd];
    };
}

-(void)tiOrder:(NSString*)pwd{
    if(pwd.length == 0) {
        [DKProgressHUD showErrorWithStatus:@"请正确输入支付密码"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:@(self.model.ID) forKey:@"orderId"];
    [dict setValue:pwd forKey:@"paypwd"];
    //买入订单
    if (self.type == 0) { //卖出订单--无法选择数量
        [dict setValue:self.model.ChinaANumber forKey:@"biCount"];
        [dict setValue:self.model.PriceRMB forKey:@"biPrice"];
    }else{
        JiaoYiDetailViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        CGFloat floatCount = [cell.numField.text floatValue];
//        if(floatCount>[self.model.LimitMax floatValue] || floatCount < [self.model.LimitMix floatValue]){
//            [DKProgressHUD showErrorWithStatus:@"请输入限额内的币数"];
//            return;
//        }
        [dict setValue:@(floatCount) forKey:@"biCount"];
        [dict setValue:self.model.PriceRMB forKey:@"biPrice"];
    }
    
    [DKProgressHUD showLoading];
    [taskJiaoYiService dianTransOrder:dict success:^(BaseModel *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            JiaoYiSuccessViewController *vc = [JiaoYiSuccessViewController new];
            vc.isMaiRu = self.type == 0 ? YES : NO;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [DKProgressHUD showErrorWithStatus:response.message];
        }
        
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
    
}

#pragma mark - 动态计算总数

///动态计算数
-(void)txtEditChanged:(UITextField*)sender{
    JiaoYiDetailViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSInteger numCount = [cell.numField.text integerValue] ;
    if (numCount > [self.model.ChinaANumber integerValue]) {
        [DKProgressHUD showErrorWithStatus:@"超过最大购买量"];
        return;
    }
    cell.lbPrice.text = [NSString stringWithFormat:@"%.2f",numCount * [self.model.PriceRMB floatValue]];
}


@end
